<template>
	<view class="container">
		<view class="header">
			<view class="back-button" @click="navigateBack">
				<text class="iconfont icon-back"></text>
			</view>
			<view class="page-title">我的订单</view>
		</view>
		
		<!-- 订单状态切换标签 -->
		<view class="tab-nav">
			<view 
				v-for="(tab, index) in tabs" 
				:key="index" 
				class="tab-item" 
				:class="{ active: currentTab === index }"
				@click="switchTab(index)"
			>
				<text>{{ tab.name }}</text>
				<text class="tab-indicator" v-if="currentTab === index"></text>
			</view>
		</view>
		
		<!-- 订单列表 -->
		<swiper class="order-list-container" :current="currentTab" @change="handleSwiperChange">
			<swiper-item v-for="(tab, tabIndex) in tabs" :key="tabIndex">
				<scroll-view 
					scroll-y 
					class="order-list"
					@scrolltolower="loadMoreOrders"
				>
					<!-- 空状态 -->
					<view class="empty-state" v-if="orderLists[tabIndex].length === 0">
						<text class="iconfont icon-order empty-icon"></text>
						<view class="empty-text">还没有{{ tab.name }}订单哦</view>
						<view class="empty-action" @click="navigateTo('/pages/index/index')">去寻找心仪的摄影师</view>
					</view>
					
					<!-- 订单列表 -->
					<view 
						class="order-item" 
						v-for="(order, index) in orderLists[tabIndex]" 
						:key="order.id" 
						@click="navigateToDetail(order.id)"
					>
						<view class="order-header">
							<view class="order-number">订单号：{{ order.orderNumber }}</view>
							<view class="order-status" :class="'status-' + order.status">{{ getStatusText(order.status) }}</view>
						</view>
						
						<view class="photographer-info">
							<image class="photographer-avatar" :src="order.photographerAvatar" mode="aspectFill"></image>
							<view class="photographer-details">
								<view class="photographer-name">{{ order.photographerName }}</view>
								<view class="service-name">{{ order.serviceName }}</view>
							</view>
						</view>
						
						<view class="order-details">
							<view class="detail-item">
								<text class="detail-label">拍摄时间：</text>
								<text class="detail-value">{{ order.shootingTime }}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">拍摄地点：</text>
								<text class="detail-value">{{ order.location }}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">服务价格：</text>
								<text class="detail-value price">¥{{ order.price }}</text>
							</view>
						</view>
						
						<view class="order-footer">
							<view class="order-time">{{ order.createTime }}</view>
							<view class="order-actions">
								<!-- 待付款状态 -->
								<block v-if="order.status === 'pending_payment'">
									<button class="action-button secondary" @click.stop="cancelOrder(order.id)">取消订单</button>
									<button class="action-button primary" @click.stop="payOrder(order.id)">立即支付</button>
								</block>
								
								<!-- 已支付状态 -->
								<block v-if="order.status === 'paid'">
									<button class="action-button secondary" @click.stop="contactPhotographer(order.photographerId)">联系摄影师</button>
									<button class="action-button primary" @click.stop="navigateToDetail(order.id)">查看详情</button>
								</block>
								
								<!-- 进行中状态 -->
								<block v-if="order.status === 'in_progress'">
									<button class="action-button secondary" @click.stop="contactPhotographer(order.photographerId)">联系摄影师</button>
									<button class="action-button primary" @click.stop="navigateToDetail(order.id)">查看进度</button>
								</block>
								
								<!-- 待确认状态 -->
								<block v-if="order.status === 'pending_confirmation'">
									<button class="action-button secondary" @click.stop="contactPhotographer(order.photographerId)">联系摄影师</button>
									<button class="action-button primary" @click.stop="confirmOrder(order.id)">确认完成</button>
								</block>
								
								<!-- 已完成状态 -->
								<block v-if="order.status === 'completed'">
									<button class="action-button secondary" @click.stop="downloadPhotos(order.id)" v-if="!order.isReviewed">下载照片</button>
									<button class="action-button secondary" @click.stop="writeReview(order.id)" v-if="!order.isReviewed">评价</button>
									<button class="action-button primary" @click.stop="navigateToDetail(order.id)">查看详情</button>
								</block>
								
								<!-- 已取消状态 -->
								<block v-if="order.status === 'cancelled'">
									<button class="action-button secondary" @click.stop="deleteOrder(order.id)">删除订单</button>
									<button class="action-button primary" @click.stop="reorder(order.id)">再次预约</button>
								</block>
							</view>
						</view>
					</view>
					
					<!-- 加载更多 -->
					<view class="loading-more" v-if="orderLists[tabIndex].length > 0 && hasMore[tabIndex]">
						<text class="loading-text">加载中...</text>
					</view>
					<view class="no-more" v-if="orderLists[tabIndex].length > 0 && !hasMore[tabIndex]">
						<text>没有更多订单了</text>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
		
		<!-- 底部导航 -->
		<view class="tab-bar">
			<view class="tab-item" @click="navigateTo('/pages/index/index')">
				<text class="iconfont icon-home"></text>
				<text class="tab-text">首页</text>
			</view>
			<view class="tab-item active">
				<text class="iconfont icon-order"></text>
				<text class="tab-text">订单</text>
			</view>
			<view class="tab-item" @click="navigateTo('/pages/profile/profile')">
				<text class="iconfont icon-user"></text>
				<text class="tab-text">我的</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabs: [
					{ name: '全部', status: 'all' },
					{ name: '待付款', status: 'pending_payment' },
					{ name: '进行中', status: 'in_progress' },
					{ name: '已完成', status: 'completed' },
					{ name: '已取消', status: 'cancelled' }
				],
				currentTab: 0,
				orderLists: [[], [], [], [], []],
				hasMore: [true, true, true, true, true],
				page: [1, 1, 1, 1, 1],
				pageSize: 10
			}
		},
		onLoad() {
			// 加载订单数据
			this.loadOrders();
		},
		methods: {
			// 切换选项卡
			switchTab(index) {
				this.currentTab = index;
				// 如果该选项卡无数据且hasMore为true，则加载数据
				if (this.orderLists[index].length === 0 && this.hasMore[index]) {
					this.loadOrders();
				}
			},
			
			// 处理滑动切换
			handleSwiperChange(e) {
				this.currentTab = e.detail.current;
				// 如果该选项卡无数据且hasMore为true，则加载数据
				if (this.orderLists[this.currentTab].length === 0 && this.hasMore[this.currentTab]) {
					this.loadOrders();
				}
			},
			
			// 加载订单数据
			loadOrders() {
				const tabIndex = this.currentTab;
				const status = this.tabs[tabIndex].status;
				
				// 模拟加载中
				uni.showLoading({
					title: '加载中...'
				});
				
				// 模拟网络请求
				setTimeout(() => {
					uni.hideLoading();
					
					// 模拟数据
					const mockOrders = this.getMockOrders(status, this.page[tabIndex], this.pageSize);
					
					// 更新数据
					if (mockOrders.length > 0) {
						this.orderLists[tabIndex] = [...this.orderLists[tabIndex], ...mockOrders];
						this.page[tabIndex]++;
					}
					
					// 判断是否还有更多数据
					if (mockOrders.length < this.pageSize) {
						this.hasMore[tabIndex] = false;
					}
					
					// 模拟下拉刷新结束
					uni.stopPullDownRefresh();
				}, 500);
			},
			
			// 加载更多订单
			loadMoreOrders() {
				if (this.hasMore[this.currentTab]) {
					this.loadOrders();
				}
			},
			
			// 获取模拟订单数据
			getMockOrders(status, page, pageSize) {
				// 模拟订单状态列表
				const allStatuses = [
					'pending_payment', 'paid', 'in_progress', 
					'pending_confirmation', 'completed', 'cancelled'
				];
				
				// 根据状态筛选
				let filteredStatuses = allStatuses;
				if (status === 'pending_payment') {
					filteredStatuses = ['pending_payment'];
				} else if (status === 'in_progress') {
					filteredStatuses = ['paid', 'in_progress', 'pending_confirmation'];
				} else if (status === 'completed') {
					filteredStatuses = ['completed'];
				} else if (status === 'cancelled') {
					filteredStatuses = ['cancelled'];
				}
				
				// 模拟生成订单数据
				const orders = [];
				// 模拟第一页有数据，后面页数渐少
				const count = page === 1 ? pageSize : (page === 2 ? Math.floor(pageSize / 2) : 0);
				
				for (let i = 0; i < count; i++) {
					const randomStatusIndex = Math.floor(Math.random() * filteredStatuses.length);
					const randomStatus = filteredStatuses[randomStatusIndex];
					
					orders.push({
						id: `order_${page}_${i}`,
						orderNumber: this.generateRandomOrderNumber(),
						status: randomStatus,
						photographerId: `photographer_${i}`,
						photographerName: `摄影师${i + 1}`,
						photographerAvatar: `https://randomuser.me/api/portraits/${i % 2 ? 'men' : 'women'}/${i + 1}.jpg`,
						serviceName: ['婚纱摄影', '儿童摄影', '写真摄影', '旅拍摄影', '商业摄影'][i % 5],
						shootingTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 12) + 9}:00`,
						location: ['上海市静安区南京西路', '北京市朝阳区三里屯', '广州市天河区天河路', '深圳市南山区科技园', '杭州市西湖区西湖边'][i % 5],
						price: Math.floor(Math.random() * 5000) + 500,
						createTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
						isReviewed: Math.random() > 0.5
					});
				}
				
				return orders;
			},
			
			// 生成随机订单号
			generateRandomOrderNumber() {
				return `PO${Date.now().toString().slice(-8)}${Math.floor(Math.random() * 1000)}`;
			},
			
			// 获取订单状态文本
			getStatusText(status) {
				const statusMap = {
					'pending_payment': '待付款',
					'paid': '已支付',
					'in_progress': '进行中',
					'pending_confirmation': '待确认',
					'completed': '已完成',
					'cancelled': '已取消'
				};
				return statusMap[status] || status;
			},
			
			// 取消订单
			cancelOrder(orderId) {
				uni.showModal({
					title: '取消订单',
					content: '确定要取消该订单吗？',
					success: (res) => {
						if (res.confirm) {
							// 模拟取消订单操作
							setTimeout(() => {
								// 更新本地数据状态
								this.updateOrderStatus(orderId, 'cancelled');
								
								uni.showToast({
									title: '订单已取消',
									icon: 'success'
								});
							}, 500);
						}
					}
				});
			},
			
			// 支付订单
			payOrder(orderId) {
				uni.showModal({
					title: '订单支付',
					content: '确定要支付该订单吗？',
					success: (res) => {
						if (res.confirm) {
							// 跳转到支付页面
							uni.navigateTo({
								url: `/pages/payment/payment?orderId=${orderId}`
							});
						}
					}
				});
			},
			
			// 联系摄影师
			contactPhotographer(photographerId) {
				// 阻止冒泡，避免触发跳转详情
				event.stopPropagation();
				
				// 模拟联系操作
				uni.showToast({
					title: '正在连接客服...',
					icon: 'none'
				});
				
				// 实际应用中应跳转到聊天页面
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/chat/chat?photographerId=${photographerId}`
					});
				}, 1000);
			},
			
			// 确认订单
			confirmOrder(orderId) {
				uni.showModal({
					title: '确认订单',
					content: '确认摄影服务已完成？',
					success: (res) => {
						if (res.confirm) {
							// 模拟确认操作
							setTimeout(() => {
								// 更新本地数据状态
								this.updateOrderStatus(orderId, 'completed');
								
								uni.showToast({
									title: '订单已确认完成',
									icon: 'success'
								});
							}, 500);
						}
					}
				});
			},
			
			// 下载照片
			downloadPhotos(orderId) {
				// 模拟下载操作
				uni.showLoading({
					title: '准备下载...'
				});
				
				setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '照片已下载到相册',
						icon: 'success'
					});
				}, 1500);
			},
			
			// 写评价
			writeReview(orderId) {
				uni.navigateTo({
					url: `/pages/review/review?orderId=${orderId}`
				});
			},
			
			// 删除订单
			deleteOrder(orderId) {
				uni.showModal({
					title: '删除订单',
					content: '确定要删除该订单记录吗？删除后无法恢复',
					success: (res) => {
						if (res.confirm) {
							// 模拟删除操作
							setTimeout(() => {
								// 从所有列表中删除该订单
								for (let i = 0; i < this.orderLists.length; i++) {
									this.orderLists[i] = this.orderLists[i].filter(order => order.id !== orderId);
								}
								
								uni.showToast({
									title: '订单已删除',
									icon: 'success'
								});
							}, 500);
						}
					}
				});
			},
			
			// 再次预约
			reorder(orderId) {
				// 查找订单信息
				let orderInfo = null;
				for (let i = 0; i < this.orderLists.length; i++) {
					const found = this.orderLists[i].find(order => order.id === orderId);
					if (found) {
						orderInfo = found;
						break;
					}
				}
				
				if (orderInfo) {
					// 跳转到摄影师详情页
					uni.navigateTo({
						url: `/pages/photographer_detail/photographer_detail?id=${orderInfo.photographerId}`
					});
				}
			},
			
			// 更新订单状态
			updateOrderStatus(orderId, newStatus) {
				// 更新所有列表中该订单的状态
				for (let i = 0; i < this.orderLists.length; i++) {
					this.orderLists[i] = this.orderLists[i].map(order => {
						if (order.id === orderId) {
							return { ...order, status: newStatus };
						}
						return order;
					});
				}
			},
			
			// 导航到订单详情
			navigateToDetail(orderId) {
				uni.navigateTo({
					url: `/pages/order_detail/order_detail?id=${orderId}`
				});
			},
			
			// 导航到指定页面
			navigateTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			
			// 返回上一页
			navigateBack() {
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 导入SCSS变量文件和共享样式 */
	@import '../../uni.scss';
	@import '../../common/styles.scss';

	// Define SCSS variables to prevent undefined variable errors
	$primary-color: #07C160;
	$secondary-color: #f8f8f8;
	$border-color: #eaeaea;
	$dark-text: #333333;
	$light-text: #999999;
	
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 50px;
	}
	
	/* 头部 */
	.header {
		position: relative;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		padding: 0 15px;
		border-bottom: 1px solid $border-color;
	}
	
	.back-button {
		position: absolute;
		left: 15px;
		top: 50%;
		transform: translateY(-50%);
		font-size: 18px;
		color: $dark-text;
	}
	
	.page-title {
		font-size: 18px;
		font-weight: 500;
		color: $dark-text;
	}
	
	/* 标签导航 */
	.tab-nav {
		display: flex;
		background-color: #fff;
		border-bottom: 1px solid $border-color;
	}
	
	.tab-item {
		flex: 1;
		height: 44px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		color: $light-text;
		position: relative;
	}
	
	.tab-item.active {
		color: $primary-color;
		font-weight: 500;
	}
	
	.tab-indicator {
		position: absolute;
		bottom: 0;
		width: 20px;
		height: 3px;
		background-color: $primary-color;
		border-radius: 2px;
	}
	
	/* 订单列表容器 */
	.order-list-container {
		flex: 1;
		height: calc(100vh - 139px); /* 减去头部、标签导航和底部导航的高度 */
	}
	
	.order-list {
		height: 100%;
		padding: 15px;
	}
	
	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 0;
	}
	
	.empty-icon {
		font-size: 120px;
		margin-bottom: 20px;
	}
	
	.empty-text {
		font-size: 15px;
		color: $light-text;
		margin-bottom: 20px;
	}
	
	.empty-action {
		font-size: 14px;
		color: $primary-color;
		padding: 8px 20px;
		border: 1px solid $primary-color;
		border-radius: 20px;
	}
	
	/* 订单项 */
	.order-item {
		background-color: #fff;
		border-radius: 10px;
		margin-bottom: 15px;
		padding: 15px;
		box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
	}
	
	.order-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 15px;
	}
	
	.order-number {
		font-size: 13px;
		color: $light-text;
	}
	
	.order-status {
		font-size: 13px;
		font-weight: 500;
	}
	
	.status-pending_payment {
		color: #ff9800;
	}
	
	.status-paid, .status-in_progress, .status-pending_confirmation {
		color: #2196f3;
	}
	
	.status-completed {
		color: #4caf50;
	}
	
	.status-cancelled {
		color: #9e9e9e;
	}
	
	.photographer-info {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
		padding-bottom: 15px;
		border-bottom: 1px solid $border-color;
	}
	
	.photographer-avatar {
		width: 50px;
		height: 50px;
		border-radius: 25px;
		margin-right: 10px;
	}
	
	.photographer-name {
		font-size: 16px;
		font-weight: 500;
		color: $dark-text;
		margin-bottom: 5px;
	}
	
	.service-name {
		font-size: 14px;
		color: $light-text;
	}
	
	.order-details {
		padding-bottom: 15px;
		border-bottom: 1px solid $border-color;
	}
	
	.detail-item {
		margin-bottom: 8px;
		font-size: 14px;
	}
	
	.detail-item:last-child {
		margin-bottom: 0;
	}
	
	.detail-label {
		color: $light-text;
	}
	
	.detail-value {
		color: $dark-text;
	}
	
	.detail-value.price {
		color: #ff5722;
		font-weight: 500;
	}
	
	.order-footer {
		padding-top: 15px;
		display: flex;
		flex-direction: column;
	}
	
	.order-time {
		font-size: 12px;
		color: $light-text;
		margin-bottom: 10px;
	}
	
	.order-actions {
		display: flex;
		justify-content: flex-end;
	}
	
	.action-button {
		padding: 0 15px;
		height: 32px;
		line-height: 32px;
		font-size: 13px;
		border-radius: 16px;
		margin-left: 10px;
		background-color: transparent;
	}
	
	.action-button.primary {
		background-color: $primary-color;
		color: #fff;
	}
	
	.action-button.secondary {
		border: 1px solid $border-color;
		color: $dark-text;
	}
	
	/* 加载更多 */
	.loading-more, .no-more {
		text-align: center;
		padding: 15px 0;
		font-size: 14px;
		color: $light-text;
	}
	
	/* 底部导航 */
	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		background-color: #fff;
		display: flex;
		box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.05);
	}
	
	.tab-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	
	.tab-item .iconfont {
		font-size: 20px;
		margin-bottom: 2px;
		color: #999;
	}
	
	.tab-item .tab-text {
		font-size: 12px;
		color: #999;
	}
	
	.tab-item.active .iconfont,
	.tab-item.active .tab-text {
		color: $primary-color;
	}
	
	/* iconfont */
	.icon-back:before {
		content: "\e679";
	}
	
	.icon-home:before {
		content: "\e7c6";
	}
	
	.icon-order:before {
		content: "\e63f";
	}
	
	.icon-user:before {
		content: "\e7ae";
	}
</style> 